package com.wongsir.javatool.imageUtil;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import com.wongsir.javatool.fileUtil.FileUtil;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;

/**
 * @Description: 获取图片流相关信息工具类
 * @author hjd
 * @date 2018年7月2日
 */
public class ImageUtil {
	/**
	 * 通过base64编码获取图片文件大小
	 * @param base64Str 图片base64格式编码字符串
	 * @return
	 */
	public static int getImgSize(String base64Str){
		int fileLen = 0;
		if(base64Str != null && !"".equals(base64Str)) {
			base64Str = base64Str.substring(22);//去除base64头部
			int equ = base64Str.indexOf('=');
			if(equ > 0){
				base64Str = base64Str.substring(0, equ);
			}
			int strLen = base64Str.length();//字符流大小，单位为字节
			fileLen = strLen - (strLen/8)*2; //文件流大小，单位为字节
		}
		return fileLen;
	}
	
	/**
	 * 获取文件流大小，单位是字节
	 * @param in 文件流
	 * @return
	 */
	public static int getImgSize(InputStream in) {
		byte[] buf = new byte[1024];
		int len = -1;
		int size = 0;
		try {
			while((len = in.read(buf))!= -1) {
				size += len;
			}
			in.reset();
		} catch (IOException e) {
			e.printStackTrace();
			return 0;
		}
		return size;
	}
	
	/**
	 * 将BufferedImage保存成图片到本地
	 * @param in 网络图片输入流InputStream
	 * @throws Exception 
	 */
	public static void saveImg(InputStream in,String filepath,String filename) throws Exception{
		BufferedImage img = ImageIO.read(in);
		in.reset();
		if(img != null){
			FileUtil.mkdirs(filepath);
			StringBuilder path = new StringBuilder();
			path.append(filepath).append("/").append(filename);
			File file = new File(path.toString());
			ImageIO.write(img, "jpg", file);
		}else{
			throw new Exception("图片流为null"); 
		}
	}
	
	/**
	 * 获取图片流
	 * @param imageUrl
	 * @return
	 * @throws Exception 
	 */
	public static InputStream getImgIO(String imageUrl) throws Exception{
		imageUrl = URLUtil.decode(imageUrl);
		InputStream in = null;
		cn.hutool.http.HttpResponse  httpResponse = HttpRequest.get(imageUrl).timeout(10000).execute();
		if(httpResponse.getStatus() == 200) {
			in = HttpRequest.get(imageUrl).timeout(10000).execute().bodyStream();
		}else {
			throw new Exception("获取图片失败，http状态码："+httpResponse.getStatus());
		}
		return in;
	}
}
